package cn.yi.springboot.druid.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


/**
 * 配置第一个数据源，当存在多个数据源时，需要指定其中一个数据源Bean的优先级，但不可两个都使用Primary
 * @author: yiz
 * @date: 2018/8/1 14:35
 **/
@Configuration
@MapperScan(basePackages = "cn.yi.springboot.druid.two.mapper",sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DruidTwoConfig {
    /**
     * 多数据源时，第二个数据源不要使用Primary
     * @return
     */
    @Bean("dataSourceTwo")
    @ConfigurationProperties("spring.datasource.druid.two")
    public DataSource dataSourceTwo(){
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "twoSqlSessionFactory")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("dataSourceTwo") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

}
